package com.powergisol.gis.geom;

import com.powergisol.gis.feature.SimpleFeatureGenerator;
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.geom.Point;
import org.geotools.data.simple.SimpleFeatureCollection;
import org.geotools.data.simple.SimpleFeatureIterator;
import org.geotools.factory.CommonFactoryFinder;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.type.AttributeDescriptor;
import org.opengis.filter.Filter;
import org.opengis.filter.FilterFactory2;

import java.util.*;

public class SpatialRelationship {

    /**
     * 判断是否相等
     *
     * @param typeOne
     * @param typeTwo
     * @return
     */
    public boolean equals(GeoType typeOne, GeoType typeTwo) {
        Geometry geometry1 = typeOne.toGeometry();
        Geometry geometry2 = typeTwo.toGeometry();
        return geometry1.equals(geometry2);
    }

    /**
     * 判断typeOne 是否被包含在 typeTwo 内
     *
     * @param typeOne
     * @param typeTwo
     * @return
     */
    public boolean within(GeoType typeOne, GeoType typeTwo) {
        Geometry geometry1 = typeOne.toGeometry();
        Geometry geometry2 = typeTwo.toGeometry();
        return geometry1.within(geometry2);
    }


    /**
     * @param list
     * @param polygon
     * @return
     */
    public List<GeoPoint> intersects(List<GeoPoint> list, GeoPolygon polygon) {



        List<GeoPoint> points = new ArrayList<>();
        SimpleFeatureGenerator generator = new SimpleFeatureGenerator();

        SimpleFeatureCollection collection = generator.createCollection(list);

        FilterFactory2 ff = CommonFactoryFinder.getFilterFactory2();

        Filter filter = ff.intersects(ff.property("the_geom"), ff.literal(polygon.toGeometry()));

        SimpleFeatureCollection subCollection = collection.subCollection(filter);

        SimpleFeatureIterator iterator = subCollection.features();

        while (iterator.hasNext()) {
            SimpleFeature next = iterator.next();


            List<AttributeDescriptor> attributeDescriptors = next.getFeatureType().getAttributeDescriptors();


            Object defaultGeometry = next.getDefaultGeometry();
            if (defaultGeometry instanceof Point) {
                Point point = (Point) defaultGeometry;
                GeoPoint geoPoint = new GeoPoint(point.getX(), point.getY());
                Map<String, Object> values = new HashMap<>();

                for (AttributeDescriptor attributeDescriptor : attributeDescriptors) {
                    String key = attributeDescriptor.getLocalName();
                    Object object = next.getAttribute(key);
                    values.put(key, object);
                }
                geoPoint.setProperties(values);
                points.add(geoPoint);
            }
        }

        iterator.close();
        return points;

    }


}
